﻿using Engine;
using Game;
using GameEntitySystem;
using TemplatesDatabase;

namespace JackODummy
{
	public class ComponentJackODummy : Component, IUpdateable
	{
		public SubsystemTerrain SubsystemTerrain
		{
			get; set;
		}
		public SubsystemAudio SubsystemAudio
		{
			get; set;
		}
		public SubsystemParticles SubsystemParticles
		{
			get; set;
		}
		public ComponentBody ComponentBody
		{
			get; set;
		}
		public ComponentDamage ComponentDamage
		{
			get; set;
		}

		public Point3? Anchor
		{
			get; set;
		}
		public Quaternion? Rotation
		{
			get; set;
		}
		public bool WasHit
		{
			get; set;
		}
		public float ImpulseOrder
		{
			get; set;
		}
		public float StunTime
		{
			get; set;
		}
		public UpdateOrder UpdateOrder => UpdateOrder.Default;
		public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
		{
			base.Load(valuesDictionary, idToEntityMap);
			SubsystemTerrain = Project.FindSubsystem<SubsystemTerrain>(throwOnError: true);
			SubsystemAudio = Project.FindSubsystem<SubsystemAudio>(throwOnError: true);
			SubsystemParticles = Project.FindSubsystem<SubsystemParticles>(throwOnError: true);
			ComponentBody = Entity.FindComponent<ComponentBody>(throwOnError: true);
			ComponentDamage = Entity.FindComponent<ComponentDamage>(throwOnError: true);
			Rotation = valuesDictionary.GetValue("Rotation", Quaternion.Identity);
		}
		public override void Save(ValuesDictionary valuesDictionary, EntityToIdMap entityToIdMap)
		{
			base.Save(valuesDictionary, entityToIdMap);
			if(Rotation.HasValue)
			valuesDictionary.SetValue("Rotation", Rotation.Value);
		}
		public void Update(float dt)
		{
			if (Anchor.HasValue)
			{
				Vector3 position = new(Anchor.Value.X + 0.5f, Anchor.Value.Y, Anchor.Value.Z + 0.5f);
				if (ComponentBody.Position != position)
					ComponentBody.Position = position;
			}
			if (Rotation.HasValue && ComponentBody.Rotation != Rotation)
			{
				ComponentBody.Rotation = Rotation.Value;
			}
			if (ComponentDamage.HitpointsChange >= 0 && JackOUtility.SubsystemTime.PeriodicGameTimeEvent(1.0, 0))
				ComponentDamage.Hitpoints = 1f;
			StunTime = MathUtils.Max(0.0f, StunTime - dt);
		}
	}
}
